適合用在複製一樣的物件,大量生成。這一次主要是想用實例化來生成蘋果,在場中自動放很多顆蘋果!!
先來看定義
//宣告建構式
public static Object Instantiate(Object original);
public static Object Instantiate(Object original, Transform parent);
public static
Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
※沒有要旋轉的時候,旋轉向量可以填這個:Quaternion.identity
1.先創建好要複製的物件
2.寫好腳本,掛在空物件上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InstantiateApple : MonoBehaviour
{
//宣告生成物件
public GameObject apple;
//設置三個生成位置
Vector3 position1 = new Vector3(-1.039978f,-0.330002f,0.0f);
Vector3 position2 = new Vector3(-0.039978f,-1.330002f,0.0f);
Vector3 position3 = new Vector3(-0.039978f,-0.330002f,0.0f);
//設置旋轉
Quaternion rotation1 = new Quaternion(0,0,0,0);
void Start()
{
Instantiate(apple,position1, rotation1);
Instantiate(apple,position2, new Quaternion(0,0,0,0));
Instantiate(apple,position3, Quaternion.identity);
}
掛完腳本之後記得將要複製的物件拖曳進去。
3.設定好之後執行
1.做法都一樣,改腳本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InstantiateApple : MonoBehaviour
{
//宣告要生成的物件
public GameObject apple;
//宣告生成物件的父物件
public Transform appleClass;
//三個生成位置
Vector3 position1 = new Vector3(-1.039978f,-0.330002f,0.0f);
Vector3 position2 = new Vector3(-0.039978f,-1.330002f,0.0f);
Vector3 position3 = new Vector3(-0.039978f,-0.330002f,0.0f);
//設置旋轉
Quaternion rotation1 = new Quaternion(0,0,0,0);
void Start()
{
Instantiate(apple,position1, rotation1,appleClass);
Instantiate(apple,position2, new Quaternion(0,0,0,0),appleClass);
Instantiate(apple,position3, Quaternion.identity,appleClass);
}
}
2.結果